<template>
  <view class="order-box">
    <hs-status-bar type="capsule"></hs-status-bar>
    <top-bar :title="'提交订单'" :haveBack="true"></top-bar>
    <scroll-view scroll-y="true" class="order-content" v-if="!checkouting">
      <!-- <navigator> -->
      <view class="address" @click="chooseAdress" v-if="isStore == ''">
        <view class="t1"> 选择地址: </view>
        <view class="t2">
          {{
            adressInfo.addressLine ||
            (addressList.length > 0 ? "选择收货地址" : "新增收货地址")
          }}
        </view>
        <view class="t3">
          {{
            `${adressInfo.receiverName || ""}   ${
              adressInfo.receiverPhone || ""
            }`
          }}
        </view>
        <image
          class="edit"
          src="@/static/images/icon/vector.png"
          mode="aspectFit"
        ></image>
      </view>
      <!-- </navigator> -->

      <view class="order">
        <view class="title"> caseform </view>
        <view
          class="order-item"
          v-for="item of orderInfo.productList"
          :key="item.id"
        >
          <image
            class="pic"
            :src="item.imageUrl"
            mode="aspectFit"
            @click="previewImage(item.imageUrl)"
          ></image>
          <view class="left-text">
            <view class="name">
              <text>{{ item.name }}</text>
              <text class="right"> ￥{{ item.displayTotalPrice }} </text>
            </view>
            <view class="model">
              <!-- 苹果iphone16 pro max -->
               {{ item.materialName }}
              <text class="right"> ×{{ item.quantity }} </text>
            </view>
          </view>
        </view>
      </view>
      <view class="other">
        <view class="other-item" @click="open">
          <text>使用优惠券</text>
          <view class="hs-row-center">
            <view>{{ couponName }}</view>
            <view class="hs-margin-left-20">
              <image
                class="coupons-arrow"
                src="@/static/images/icon/vector.png"
                mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>
        <view class="other-item">
          <text>商品总价</text>
          <text>￥ {{ orderInfo.displayPhoneCaseAmount }}</text>
        </view>
		<view class="other-item">
			<text>优惠金额</text>
			<view>
				<text v-if="orderInfo.displayCouponAmount > 0" class="displayCouponAmount">减￥{{orderInfo.displayCouponAmount}}</text>
				<text v-else>￥0</text>
				
			</view>
			
		</view> 
        <view class="other-item">
          <text>邮费</text>
          <!-- <text>{{adressInfo.id?'￥ '+orderInfo.displayShippingFee:'填写地址后获取'}}</text> -->
          <text>免邮费</text>
        </view>
        <!-- <view class="amount">
					<text>优惠</text>
					<text>{{orderInfo.phoneCaseAmount}}</text>
				</view> -->
      </view>
    </scroll-view>

    <u-popup
      :show="couponShow"
      :round="10"
      :closeable="true"
      @close="close"
      @open="open"
    >
      <view class="coupons content hs-margin-top-100">
        <view class="coupons-title hs-fz-40 hs-text-center">优惠券</view>
        <scroll-view
          scroll-y="true"
          @scrolltolower="scrolltolower"
          class="coupon-container"
        >
          <view class="coupon-container">
            <!-- 不使用优惠券选项 -->
            <view
              class="coupon no-coupon"
              :class="{ selected: couponId === '' }"
              @click="handleSelect('none')"
            >
              <view class="radio-wrapper">
                <view class="radio">
                  <view v-if="couponId === ''" class="radio-inner"></view>
                </view>
              </view>
              <text class="no-coupon-text">不使用优惠券</text>
            </view>

            <!-- 优惠券列表 -->
            <view
              class="coupon"
              v-for="(item, index) in couponsList"
              :key="index"
              :class="[item.status, { selected: couponId === item.id }]"
              @click="handleSelect(item)"
            >
              <view class="left">
                <view class="price">
                  <text class="symbol">¥</text>
                  <text class="number">{{ item.amount }}</text>
                </view>
                <view class="condition">{{ item.condition }}</view>
              </view>

              <view class="right">
                <!-- 单选按钮 -->
                <view class="radio-wrapper">
                  <view class="radio">
                    <view
                      v-if="couponId === item.id"
                      class="radio-inner"
                    ></view>
                  </view>
                </view>

                <view class="title">{{ item.name }}</view>
                <view class="time">有效期至{{item.validEndTime}}</view>
                <view class="tags">
                  <text
                    v-for="(tag, tIndex) in item.tags"
                    :key="tIndex"
                    class="tag"
                    >{{ tag }}</text
                  >
                </view>
              </view>

              <!-- 锯齿效果 -->
              <view class="sawtooth"></view>
              <!-- 角标 -->
              <view class="corner-tag">新人专享</view>

              <view class="sawtooth"></view>
            </view>
          </view>
        </scroll-view>
      </view>
    </u-popup>

    <view class="to-pay" v-if="!checkouting">
      <view class="amount" v-if=" isStore == ''">
        {{
          adressInfo.id ? '￥' + orderInfo.displayTotalAmount : "填写地址后获取"
        }}
        
      </view>
      <view class="amount" v-else>
        {{'￥' + orderInfo.displayTotalAmount}}
      </view>
      <view
        class="pay"
        @click="toPay"
        :class="{ disable: (!adressInfo.id || orderData.length == 0) && isStore == '' }"
      >
        去支付
      </view>
    </view>
  </view>
</template>

<script>
import { mapGetters, mapActions } from "vuex";
import { checkout, createOrder, availableList } from "@/api/product.js";
import { paymentToOrder } from "@/utils/utils.js";
import toast from "../../uni_modules/uview-ui/libs/config/props/toast";
export default {
  data() {
    return {
      couponName: "",
      couponId: 0,
      orderInfo: {},
      adressInfo: {},
      orderData: [],
      checkouting: true,
      couponShow: false,
      couponsList: [],
    };
  },
  computed: {
    ...mapGetters(["trolleyList", "defaultAddress", "addressList", 'isStore']),
  },
  methods: {
    ...mapActions(["getAddressList"]),
    // 选择地址
    chooseAdress() {
      if (this.addressList.length == 0) {
        uni.navigateTo({
          url: "/pages/order/adressEdit",
        });
      } else {
        uni.navigateTo({
          url: "/pages/order/adress",
        });
      }
    },
    // 请求并加载订单信息
    getCheckoutInfo() {
      uni.showLoading({ title: '加载中', mask: true });
      let postData = {
        addressId: this.adressInfo.id,
        couponId: this.couponId,
        customProductList: this.orderData,
      };
      console.log("postData", postData);
      checkout(postData).then((res) => {
        this.orderInfo = res.data;
        // this.couponName = res.data.coupon.name;
        if(this.couponsList.filter((d)=>d.id==res.data.coupon.id).length > 0){
          this.couponName = res.data.coupon.name;
          this.couponId = res.data.coupon.id;
        }else if(this.couponsList.length >0 && res.data.coupon.name == ''){
          this.couponName = this.couponsList.length + '张可用优惠券';
          
        }else{
          this.couponName = '暂无优惠券';
        }
      }).catch(err => {
        uni.showToast({ title: '加载失败', icon: 'none' });
      }).finally(() => {
        uni.hideLoading(); // 确保始终执行
        this.checkouting = false;
      });
    },
    // 提交订单 关闭订单页跳转去支付页面（提交订单之后离开不会再回到这个页面
    toPay() {
      if(this.addressList.length == 0){
        uni.showToast({ title: '请选择地址', icon: 'none' });
        return;
      }
      if ((!this.adressInfo.id || this.orderData.length == 0 ) && this.isStore == '') return;

      let postData = {
        // addressId: this.adressInfo.id,
        addressId: this.isStore ? '' : this.adressInfo.id,
        printerId:  this.isStore ? this.isStore : '',// 打印机id
		    couponId: this.couponId,
        customProductList: this.orderData,
      };
	  let isDiscounts = false;
	  if(this.orderInfo.displayTotalAmount <= 0){
		isDiscounts = true;
	  }
      createOrder(postData).then((res) => {
        paymentToOrder(res.data.orderId,isDiscounts);
        // uni.redirectTo({
        // 	url: `/pages/order/pay?amount=${res.data.totalAmount}&orderId=${res.data.orderId}&time=${res.data.remainingPaymentTime}`,
        // })
      });
    },
    // 放大图片预览
    previewImage(imageUrl) {
      let arr = [imageUrl];
      uni.previewImage({
        current: 0,
        urls: arr,
      });
    },
    open() {
		if(this.couponsList.length === 0) {
			uni.$u.toast('暂无可用优惠券');
			return
		}
      this.couponShow = true;
    },
    close() {
      setTimeout(() => {
        this.couponShow = false;
      }, 300);
    },
    // 滑动到底部
    scrolltolower() {
      // if (this.templateList.length < this.pageSize) return
      // this.getTemplateList(this.templateList[this.templateList.length - 1].id)
    },
    // 获取可用优惠券列表
    async getAvailableList() {
      await availableList().then((res) => {
        if (res.code === 200) {
          this.couponsList = res.data;
        } else {
          uni.$u.toast(res.msg);
        }
        console.log("getAvailableList", res);
      });
    },
    handleSelect(item) {
      console.log("handleSelect1", item);
      if (item === "none") {
        this.couponId = "";
        // this.couponName = "不使用优惠券";
      } else {
        this.couponId = item.id;
        this.couponName = item.name;
      }
	  console.log('CouponName After:', this.couponName);
      //   this.$emit('change', value)
      console.log("handleSelect2", this.couponId);
      this.getCheckoutInfo();
      this.close();
    },
  },
  onShow() {
    let orderAdress = uni.getStorageSync("orderAdress");
    if (orderAdress.id) {
      this.adressInfo = uni.getStorageSync("orderAdress");
    } else {
      this.adressInfo = {};
    }
    uni.$u.debounce(() => {
      try {
       this.getCheckoutInfo();
       this.getAvailableList();
      } finally {
        uni.hideLoading(); // 确保最终执行
      }
    }, 500);
  },
  onHide() {},
  onLoad() {
    this.orderData = uni.getStorageSync("orderData");
    this.getAddressList().then(() => {
      console.log("this.isStore", this.isStore);
      console.log("!this.isStore", !this.isStore);
      if( !this.isStore ) {
        if (this.addressList.length == 0) {
          console.log("/pages/order/adressEdit?intoType=2");
          // uni.navigateTo({
          //   url: "/pages/order/adressEdit?intoType=2",
          // });
        } else if (this.addressList.length > 0) {
          (this.adressInfo = this.defaultAddress.id
            ? this.defaultAddress
            : this.addressList[0]),
            uni.setStorageSync("orderAdress", this.adressInfo);
        }
      }
      uni.$u.debounce(() => {
        this.getCheckoutInfo();
        this.getAvailableList();
      }, 500);
    });
  },
  onUnload() {
    uni.removeStorageSync("orderAdress");
    uni.removeStorageSync("orderData");
  },
  watch: {
    couponName(newValue, oldValue) {
      console.log("couponName", newValue);
    //   this.couponName = newValue
    },
  },
};
</script>

<style lang="scss">
.order-box {
  width: 100%;
  display: flex;
  flex-direction: column;
  height: 100%;

  .order-content {
    padding: 15rpx 19rpx;
    box-sizing: border-box;
    flex-grow: 1;
    overflow: hidden;

    .address,
    .order,
    .other {
      width: 100%;
      background: #fff;
      border-radius: 26rpx;
      margin-bottom: 28rpx;
    }

    .address {
      height: 196rpx;
      padding: 35rpx 18rpx 26rpx;
      font-weight: 600;
      color: #3d3d3d;
      position: relative;
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .t1 {
        font-size: 26rpx;
      }

      .t2 {
        width: calc(100% - 53rpx);
        font-size: 35rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .t3 {
        font-size: $uni-font-size-sm;
        color: #979797;
        font-weight: 500;
      }

      .edit {
        width: 14rpx;
        height: 26rpx;
        position: absolute;
        top: 103rpx;
        right: 24rpx;
      }
    }

    .order {
      padding: 26rpx 17.5rpx;
      display: flex;
      flex-direction: column;

      .title {
        margin: 0 0 26rpx 22.7rpx;
        font-size: 26rpx;
        font-weight: bold;
      }

      .order-item {
        height: 200rpx;
        overflow: hidden;
        display: flex;
        border-bottom: 1rpx solid #d8d8d8;
        margin-bottom: 52.6rpx;
        font-weight: 600;
        padding-bottom: 48rpx;
        justify-content: space-between;

        &:last-child {
          border-bottom: none;
        }

        .pic {
          height: 200rpx;
          width: 200rpx;
          margin-left: 22.7rpx;
          flex-shrink: 0;
        }

        .left-text {
          margin-left: 30rpx;
          display: flex;
          flex-grow: 1;
          flex-direction: column;
          justify-content: space-evenly;

          .name {
            font-size: 24.5rpx;
            color: #3d3d3d;
            display: flex;
            justify-content: space-between;
            align-items: baseline;

            .right {
              float: right;
              text-align: right;
              font-size: 38.55rpx;
              margin-right: 12.3rpx;
              width: 127rpx;
              overflow: hidden;
            }
          }

          .model {
            font-size: 21.03rpx;
            color: #979797;

            .right {
              float: right;
              text-align: right;
              font-size: 28rpx;
              margin-right: 12.3rpx;
              color: #3d3d3d;
              font-weight: normal;
            }
          }
        }
      }
    }

    .other {
      padding: 35rpx 18rpx 26rpx;
      font-size: 28rpx;
      font-weight: bold;
      line-height: 3;

      .other-item {
        display: flex;
        justify-content: space-between;

		.displayCouponAmount{
			color: red;
		}

        .coupons-arrow {
          width: 14rpx;
          height: 26rpx;
        }
      }
    }
  }

  .to-pay {
    width: calc(100% - 30rpx);
    height: 104rpx;
    background-color: #d8d8d8;
    border-radius: 52rpx;
    display: flex;
    padding: 12rpx 10rpx 10rpx 30rpx;
    justify-content: space-between;
    margin-left: 15rpx;
    margin-bottom: 17rpx;

    .amount {
      font-size: 35.05rpx;
      line-height: 80rpx;
      color: #333333;
      font-weight: 700;
    }

    .pay {
      width: 245rpx;
      height: 80rpx;
      border-radius: 40rpx;
      background: #333333;
      font-size: 35.05rpx;
      color: #fff;
      text-align: center;
      line-height: 80rpx;
      &.disable {
        opacity: 0.4;
      }
    }
  }
  //   优惠券
  .coupon-container {
    width: 690rpx;
    margin: 0 auto;
    height: 500rpx;
    .coupon {
      position: relative;
      height: 220rpx;
      background: #fff;
      border-radius: 16rpx;
      margin: 30rpx 0rpx;
      display: flex;
      overflow: hidden;
      border: 2rpx solid #eee;
      transition: all 0.2s ease;

      &.selected {
        border-color: #ff3366;
        box-shadow: 0 4rpx 16rpx rgba(255, 51, 102, 0.15);
      }

      &.no-coupon {
        height: 100rpx;
        align-items: center;
        padding: 0 30rpx;
        .no-coupon-text {
          font-size: 32rpx;
          color: #333;
          margin-left: 20rpx;
        }
      }

      // 单选按钮样式
      .radio-wrapper {
        position: absolute;
        right: 30rpx;
        top: 50%;
        transform: translateY(-50%);
        z-index: 2;

        .radio {
          width: 40rpx;
          height: 40rpx;
          border: 2rpx solid #ddd;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          transition: all 0.2s ease;

          .radio-inner {
            width: 24rpx;
            height: 24rpx;
            background: #ff3366;
            border-radius: 50%;
          }
        }
      }

      .left {
        width: 260rpx;
        padding: 40rpx 30rpx;
        background: linear-gradient(135deg, #ff3366, #ff6b6b);
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        color: #fff;

        .price {
          .symbol {
            font-size: 36rpx;
          }
          .number {
            font-size: 64rpx;
            font-weight: bold;
            margin-left: 8rpx;
          }
        }

        .condition {
          font-size: 24rpx;
          margin-top: 15rpx;
        }
      }

      .right {
        flex: 1;
        padding: 40rpx 30rpx 40rpx 50rpx;
        position: relative;

        .title {
          font-size: 34rpx;
          color: #333;
          font-weight: 500;
          margin-bottom: 15rpx;
        }

        .time {
          font-size: 26rpx;
          color: #666;
          margin-top: 30rpx;
        }

        .tags {
          margin-top: 20rpx;
          .tag {
            display: inline-block;
            padding: 6rpx 16rpx;
            background: rgba(255, 51, 102, 0.1);
            color: #ff3366;
            font-size: 22rpx;
            border-radius: 8rpx;
            margin-right: 12rpx;
          }
        }
      }

      // 锯齿效果
      .sawtooth {
        position: absolute;
        left: 260rpx;
        top: 0;
        bottom: 0;
        width: 20rpx;
        background: linear-gradient(
          45deg,
          transparent 25%,
          #fff 25%,
          #fff 75%,
          transparent 75%
        );
        background-size: 10rpx 10rpx;
      }

      /* 角标样式 */
      .corner-tag {
        position: absolute;
        right: -30rpx;
        top: 10rpx;
        width: 120rpx;
        height: 40rpx;
        line-height: 40rpx;
        background: #ffd700;
        color: #333;
        font-size: 20rpx;
        text-align: center;
        transform: rotate(45deg);
      }

      // 禁用状态
      &.disabled {
        opacity: 0.6;
        .left {
          background: #999;
        }
        .radio {
          border-color: #ccc !important;
          .radio-inner {
            background: #ccc !important;
          }
        }
      }
    }
  }
}
</style>
